package com.vip.file.service.impl;

import com.vip.file.model.entity.bucket.FileTypeEnum;
import com.vip.file.service.LocalSaveService;
import com.vip.file.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author： XW -> ~
 * @create： 2024/1/17 15:45
 */
@Slf4j
@Service
public class LocalSaveServiceImpl implements LocalSaveService, IOFileFilter {

    @Value("${file.save-path:/data-center/files/vip-file-manager}")
    private String savePath;

    public static String BUCKET_NAME = ".bucket";

    @PostConstruct
    public void init() {
        try {
            refresh();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void refreshBucket() {

        initRootDirectory();

        try {
            refresh();
        } catch (IOException e) {
            log.error("出错啦...", e);
        }
    }

    @Override
    public File addFile(File file) {
        return addFile(file.getPath());
    }

    @Override
    public File addFile(String fileName) {
        String filePath = getFilePathName(fileName);
        return new File(filePath);
    }

    @Override
    public String getFilePathName(String filePathName) {
        if (StringUtils.isEmpty(filePathName)) {
            return "";
        }
        File file = new File(filePathName);
        String name = file.getName();
        String lowerName = FileUtil.getLowerCaseSuffixName(name);
        FileTypeEnum fileTypeEnum = FileTypeEnum.getByTypeName(lowerName);

        StringBuilder fileBuilder = new StringBuilder();
        fileBuilder.append(savePath);
        fileBuilder.append(File.separator);
        fileBuilder.append(fileTypeEnum.getTypePathName());
        fileBuilder.append(File.separator);

        File newFile = new File(fileBuilder.toString() + name);
        if (newFile.isFile()) {
            return fileBuilder.append(System.currentTimeMillis()).append("_").append(name).toString();
        }

        return newFile.getPath();
    }


    public String getFilePath(String filePathName) {
        if (StringUtils.isEmpty(filePathName)) {
            return "";
        }
        File file = new File(filePathName);
        String name = file.getName();
        String lowerName = FileUtil.getLowerCaseSuffixName(name);
        FileTypeEnum fileTypeEnum = FileTypeEnum.getByTypeName(lowerName);

        StringBuilder fileBuilder = new StringBuilder();
        fileBuilder.append(savePath);
        fileBuilder.append(File.separator);
        fileBuilder.append(fileTypeEnum.getTypePathName());

        return fileBuilder.toString();
    }


    // 初始化根文件夹
    private void initRootDirectory() {
        try {
            FileUtil.mkdir(new File(savePath), false);
            FileUtil.touch(new File(savePath + File.separator + "root" + BUCKET_NAME));
        } catch (IOException e) {
            log.info("文件夹创建错误", e);
            return;
        }
    }

    private void refresh() throws IOException {

        int level = 2;
        for (int i = 0; i < level; i++) {
            createLevelDirectory(i + 1);
        }

        List<File> fileList = findBucketFile();
        log.info("size = {}", fileList.size());
    }

    private void createLevelDirectory(Integer level) {
        StringBuilder fileBuilder = new StringBuilder();
        fileBuilder.append(savePath);
        fileBuilder.append(File.separator);

        FileTypeEnum[] values = FileTypeEnum.values();
        for (FileTypeEnum fileType : values) {
            if (Objects.equals(fileType.getBucketLevel(), level)) {
                String dic = fileBuilder.toString() + fileType.getTypePathName();
                String bucketName = dic + File.separator + fileType.getTypeName() + BUCKET_NAME;
                try {
                    if (FileUtil.mkdir(new File(dic), false)) {
                        log.info("创建目录成功：{}", dic);
                    } else {
                        log.info("创建目录失败：{}", dic);
                    }
                    if (FileUtil.touch(new File(bucketName))) {
                        log.info("文件bucket成功：{}", bucketName);
                    } else {
                        log.info("文件bucket失败：{}", bucketName);
                    }
                } catch (IOException e) {
                    log.info("创建目录异常：{}", dic);
                }
            }
        }
    }

    private List<File> findBucketFile() throws IOException {
        return FileUtil.listFiles(new File(savePath), BUCKET_NAME);
    }


    public static void main(String[] args) {
        String path = "D:\\temp\\file_manager";
        String filePathName = path + File.separator + "win窗户.png";

        File file = new File("374283965");
//        log.info("file AbsolutePath = {}",file.getAbsolutePath());
//        log.info("file path = {}",file.getParentFile().getPath());
        log.info("file name = {}", file.getName());

    }

    @Override
    public boolean accept(File file) {
        return false;
    }

    @Override
    public boolean accept(File file, String s) {
        return false;
    }
}
